package cn.hlyc.mq.delay;


import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 消费者
 */
public class DelayConsumer {
    public static void main(String[] args) throws Exception{
        //先创建消费者实例
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("mq-delay-consumer-group");
        //连nameserver
        consumer.setNamesrvAddr("127.0.0.1:9876");

        //指定topic 和tag
        consumer.subscribe("delay-topic","delay-tag");
        //接受消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt m : msgs) {
                    byte[] messageByteArray = m.getBody();
                    try {
                        String messageStr = new String(messageByteArray, "utf-8");
                        System.out.println(messageStr);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                //CONSUME_SUCCESS  消费成功  RECONSUME_LATER  过一段时间  再消费
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        //启动消费者
        consumer.start();
    }
}
